//
//  MyInforViewController.m
//  Thinkape-iOS
//
//  Created by admin on 16/5/23.
//  Copyright © 2016年 TIXA. All rights reserved.
//

#import "MyInforViewController.h"
#import "AccountModel.h"
#define MAS_SHORTHAND
#define MAS_SHORTHAND_GLOBALS
#import "Masonry.h"
#import "MyInfoTool.h"
#import "MyInfoModel.h"
#import "IQKeyboardManager.h"
#import "UIImage+SKPImage.h"
#import "HomeViewController.h"
@interface MyInforViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong)UIImageView *userImageView;
@property (nonatomic,copy)NSMutableArray *rootArray;
@property (nonatomic,strong)NSMutableDictionary *rootDict;
@property (nonatomic,copy)NSString *depStr;//这个底部部门的展示

@property (nonatomic,strong)UINavigationItem *rightItem;
@property (nonatomic,assign)BOOL isChange;//判断有改变textfield
@property (nonatomic,strong)UITextField *textfield;
@property (nonatomic,strong)UIActionSheet *myActionSheet;
@property (nonatomic,assign)BOOL editHeadImg;
//@property (nonatomic,strong)NSMutableDictionary *changeDict;
//@property (nonatomic,strong)NSMutableArray *changeArray;
@end

@implementation MyInforViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _isChange = NO;
    _editHeadImg = NO;
    self.title = @"个人信息";
    //取消对第三方键盘的依赖：
    [IQKeyboardManager sharedManager].enable = NO;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = NO;
    //创建保存按钮：
    [self creatRightItem];
    [self createUI];
    AccountModel *model = [DataManager shareManager].account;
    [self requestData:model];
    self.automaticallyAdjustsScrollViewInsets = NO;
 
    [MyInfoTool getMyInformationWithSuccessfulBlock:^(id obj,id valueDict,id depStr) {
        self.rootArray = [NSMutableArray arrayWithArray:obj];
        self.rootDict = [[NSMutableDictionary alloc]initWithDictionary:valueDict];
        self.depStr = depStr;
        
        [self.tableView reloadData];
    }];
    
//    self.changeArray = [NSMutableArray new];
}

#pragma mark -- 返回方法和保存方法
//返回：
-(void)Goback
{
    if (_isChange == YES) {
        [self showAlertView];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}
//创建右按钮：
- (void)creatRightItem
{
    UIButton *rightBtn =[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    [rightBtn setTitle:@"保存" forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [rightBtn addTarget:self action:@selector(clickSaveBtn) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *saveItem =[[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = saveItem;
}
//保存：
- (void)clickSaveBtn{
    
    //http://27.115.23.126:5032/Ashx/MobileNew.ashx?ac=EditUser&u=1&pk=2&cpyid=1&svtr=<?xml version="1.0" encoding="gb2312"?><Root><Main cusercode="user" cusername="普通用户"  bankname=”工行" banknumber="955982353243532432" currentprogramid="410402"></Main></Root>&rv=3150682
    
    if (_isChange == YES) {//有上传头像或者有修改文字的操作：
        
        if (_editHeadImg == YES) {//有修改头像的存在：
            
            NSString *fbyte = @"";
            fbyte = [self bate64ForImage:self.userImageView.image];
            
//            fbyte = [self bate64Image:self.userImageView.image];
            
            NSString *strUrl = [NSString stringWithFormat:@"%@?ac=EditUserPic&u=%@&pname=%@",Web_Domain,self.uid,@"pname"];
            
            [self savePostHeadImage:strUrl imgae64:fbyte image:self.userImageView.image];
            
        }else{//只修改了文字：
        
            NSString *spliceStr = [self xmlStrSplice];
            NSString *urlStr = [NSString stringWithFormat:@"%@?ac=EditUser&u=%@&pk=%@&cpyid=1&svtr=%@",Web_Domain,self.uid,self.uid,spliceStr];
            [self savePostInformation:urlStr];
    
        }
    }else{

        [self popViewController];
//        [self.navigationController popViewControllerAnimated:YES];
    }
}


//发送保存请求：
- (void)savePostInformation:(NSString *)str
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//        [SVProgressHUD dismiss];
        
        [SVProgressHUD showSuccessWithStatus:@"修改成功"];
        [self performSelector:@selector(popViewController) withObject:nil afterDelay:0.5];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (error) {
            NSLog( @"error:%@",error.localizedDescription);
        }
        [SVProgressHUD showErrorWithStatus:@"网络错误，请稍后再试"];
    }];
    
}


- (void)savePostHeadImage:(NSString *)str imgae64:(NSString *)imagestr image:(UIImage *)image
{
    /**
     *  _imageArray.count != 0? @{@"FByte":fbyte} : nil
     */
    

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];//设置服务器允许的请求格式内容
    [manager POST:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parameters:@{@"Pic":imagestr} progress:^(NSProgress * _Nonnull uploadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSString *spliceStr = [self xmlStrSplice];
        NSString *urlStr = [NSString stringWithFormat:@"%@?ac=EditUser&u=%@&pk=%@&cpyid=1&svtr=%@",Web_Domain,self.uid,self.uid,spliceStr];
        [self savePostInformation:urlStr];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error){
        
        
        NSLog(@"error:%@",error.localizedDescription);
        [SVProgressHUD showErrorWithStatus:@"网络错误，请稍后再试"];
    
    }];

    
//    
//    [manager POST:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//
//        //UIImage *image = [UIImage imageNamed:@"111"];
//        NSData *data = UIImageJPEGRepresentation(image, 0.1f);
//        //NSData *data = UIImagePNGRepresentation(image);
//        //第一个代表文件转换后data数据，第二个代表图片的名字，第三个代表图片放入文件夹的名字，第四个代表文件的类型
//        [formData appendPartWithFileData:data name:@"1" fileName:@"image.jpg" mimeType:@"image/jpg"];
//        
//    
//        
//    
//    } progress:^(NSProgress * _Nonnull uploadProgress) {
//        NSLog(@"uploadProgress = %@",uploadProgress);
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//         NSLog(@"responseObject = %@, task = %@",responseObject,task);
//        NSString *spliceStr = [self xmlStrSplice];
//        NSString *urlStr = [NSString stringWithFormat:@"%@?ac=EditUser&u=%@&pk=%@&cpyid=1&svtr=%@",Web_Domain,self.uid,self.uid,spliceStr];
//        [self savePostInformation:urlStr];
//        
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//    
//        NSLog(@"error = %@",error);
//    }];
//    
    
    
}





- (void)popViewController
{
    [self.navigationController popViewControllerAnimated:YES];
    
}
//拼接XML字符串
- (NSString *)xmlStrSplice
{
    NSMutableString  *str  = [NSMutableString string];

    [str appendFormat:@"<?xml version= \"%@\" encoding=\"%@\"?><Root><Main",@"1.0",@"gb2312"];

    for (MyInfoModel *model in self.rootArray) {
        
        NSString *str0 = [self.rootDict objectForKey:model.Alias];
        NSLog(@"%@",str0);
        if (![str0 isEqualToString:@""]) {
            
            [str appendFormat:@" %@=\"%@\"",model.Alias,str0];
        }
    }
    
    [str appendFormat:@" userface=\"修改头像\" currentprogramid=\"410402\"></Main></Root>&rv=%@",[self.rootDict objectForKey:@"ver"]];

    return str;
}

#pragma mark -- 上传头像：
//转化为字符串啊
- (NSString *)bate64ForImage:(UIImage *)image
{
    UIImage * originImage = image;
    NSData * data = UIImageJPEGRepresentation(originImage, 0.5f);
//    NSData *data = UIImagePNGRepresentation(originImage);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    NSLog(@"%ld",encodedImageStr.length);
    return encodedImageStr;
}


#pragma mark -- 键盘通知
- (void)addNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    //获取系统发出的键盘隐藏的通知。
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    //获取系统发出的键盘frame值改变的通知。
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

#pragma mark -- 键盘通知的观察方法
- (void)keyboardWillShow:(NSNotification *)notification
{
    NSDictionary * dict = notification.userInfo;
    //获取文本框的最大Y值。
    UITextField *field = (UITextField *)[self.tableView viewWithTag:0];
    CGFloat tfMaxY = CGRectGetMaxY(field.frame);
    //获取键盘弹起之后的Y值。
    CGFloat keyboardY = [dict[UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
    //获取键盘弹起使用的时间。
    CGFloat duration = [dict[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    //判断是否遮挡
    if (tfMaxY > keyboardY) {
        //如果遮挡，添加动画，改变view的transform
        [UIView animateWithDuration:duration animations:^{
//            self.tableView.transform = CGAffineTransformMakeTranslation(0, keyboardY-tfMaxY);
            self.tableView.transform = CGAffineTransformMakeTranslation(0, -100);
        }];
    }
}
//隐藏键盘时调用：
- (void)keyboardWillHide:(NSNotification *)notification
{
    CGFloat duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    //取消transform的改变量。
    [UIView animateWithDuration:duration animations:^{
        self.tableView.transform = CGAffineTransformIdentity;
    }];
    
}
- (void)keyboardFrameChange:(NSNotification *)notification
{
    
}

- (NSDictionary *)rooDict
{
    if (!self.rootDict) {
        self.rootDict = [NSMutableDictionary new];
    }
    return self.rootDict;
}

#pragma mark -- tableView创建
- (void)createUI{
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
//    _tableView.autoresizingMask = YES;
    _tableView.tableFooterView = [[UIView alloc]init];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
}

#pragma mark -- 头像请求：
- (void)requestData:(AccountModel *)model{
    self.userImageView = [[UIImageView alloc]init];
    [self.userImageView sd_setImageWithURL:[NSURL URLWithString:[model.PicPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] placeholderImage:Default_Head_Image];
}


#pragma mark -- UITableViewDelegat && UITableViewDataSource

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0)
    {
        return 80;
    }else{
        return 44;
    }
    return 0;
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else if(section == 1){
        return self.rootArray.count;
    }else{
        return 1;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * const idetifier = @"cell";
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:idetifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:idetifier];
        
    }
    for (UIView *view in cell.contentView.subviews) {
        [view removeFromSuperview];
        
    }
    if (indexPath.section == 0) {
        //添加label：
        UILabel *label = [[UILabel alloc]init];
        [cell.contentView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(cell.contentView).with.insets(UIEdgeInsetsMake(10, 20, 10, 200));
        }];
    
        label.text = @"头  像";
        self.userImageView.frame = CGRectMake(SCREEN_WIDTH - 100, 10, 60, 60);
        self.userImageView.layer.cornerRadius = 30;
        self.userImageView.clipsToBounds = YES;
        [cell.contentView addSubview:self.userImageView];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(cell.contentView).with.insets(UIEdgeInsetsMake(10, 20, 10, 200));
        }];
    
//        cell.selectionStyle = UITableViewCellSelectionStyleDefault;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//        cell.selectedBackgroundView = [[UIView alloc]init];

    }else if(indexPath.section == 1){
        
        if (self.rootArray == nil) {
            return nil;
        }

        UILabel *label = [[UILabel alloc]init];
        [cell.contentView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(cell.contentView).with.insets(UIEdgeInsetsMake(12, 20, 12, 100));
        }];
        label.text = ((MyInfoModel *)(self.rootArray[indexPath.row])).name;
        
        _textfield = [[UITextField alloc]init];
        _textfield.tag = 1024 + indexPath.row;
        _textfield.delegate = self;
        _textfield.adjustsFontSizeToFitWidth = YES;
        _textfield.textAlignment = 1;
//        _textfield.font = [UIFont systemFontOfSize:14];
        _textfield.clearButtonMode = UITextFieldViewModeWhileEditing;
        [cell.contentView addSubview:_textfield];
        [_textfield mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(cell.contentView).with.insets(UIEdgeInsetsMake(10, 150, 10, 10));
        }];

        _textfield.text = [self.rootDict objectForKey:((MyInfoModel *)(self.rootArray[indexPath.row])).Alias];
        
        if ([_textfield.text isEqualToString:@""]) {
            _textfield.placeholder = @"未填写";
            if ([((MyInfoModel *)(self.rootArray[indexPath.row])).ismust isEqualToString:@"1"]) {
//                field.placeholder = [NSString stringWithFormat:@"%@不能为空",((MyInfoModel *)(self.rootArray[indexPath.row])).name];
                _textfield.placeholder = @"不能为空";
            }
        }
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }else if(indexPath.section == 2){
        if (self.rootArray == nil) {
            return cell;
        }
        UILabel *label = [[UILabel alloc]init];
        [cell.contentView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(cell.contentView).with.insets(UIEdgeInsetsMake(10, 20, 10, 200));
        }];
        label.text = @"部  门";
    
        UILabel *label1 = [[UILabel alloc]init];
        label1.adjustsFontSizeToFitWidth = YES;
        label1.numberOfLines = 0;
        label1.textAlignment = 1;
//        label1.font = [UIFont systemFontOfSize:14];
        [cell.contentView addSubview:label1];
        [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.edges.equalTo(cell.contentView).with.insets(UIEdgeInsetsMake(10, 150, 10, 10));
            
        }];
        label1.text = self.depStr;
        cell.selected = NO;
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    return cell;
}

#pragma mark -- textFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self addNotification];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
//    field.text = [self.rootDict objectForKey:((MyInfoModel *)(self.rootArray[indexPath.row])).Alias]
    NSInteger index = textField.tag - 1024;
    _isChange = YES;
    [self.rootDict setObject:textField.text forKey:((MyInfoModel *)(self.rootArray[index])).Alias];
//    [self.changeDict setObject:textField.text forKey:((MyInfoModel *)(self.rootArray[index])).Alias];
//    [self.changeArray addObject:(MyInfoModel *)(self.rootArray[index])];
    [self.tableView reloadData];
    
}

#pragma mark -- UIAlertController
- (void)showAlertView
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"是否放弃本次编辑" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"放弃" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [alert addAction:cancleAction];
    UIAlertAction *editAction = [UIAlertAction actionWithTitle:@"继续编辑" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:editAction];
    [self presentViewController:alert animated:YES completion:nil];
    
}

- (void)dealloc
{
    
}

#pragma mark  -- 修改头像
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0) {
        _myActionSheet =[[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"选择图片",@"拍照",nil];
        [_myActionSheet showInView:self.view];
        _myActionSheet.tag = 12;
    }
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    
    if (actionSheet.tag == 12) {
        if (buttonIndex == 1) {
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            
            picker.allowsEditing = YES;
            [self presentViewController:picker animated:YES completion:nil];
        }
        if (buttonIndex == 0)
        {
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            picker.allowsEditing = YES;
            [self presentViewController:picker animated:YES completion:nil];
        }
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *originalImage = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    
    UIImage *image1 = [UIImage imageWithData:[originalImage thumbImage:originalImage]];
    image1 = [image1 fixOrientation:image1];
    self.userImageView.image = image1;
    [self.tableView reloadData];
    [picker dismissViewControllerAnimated:YES completion:nil];
    _editHeadImg = YES;
    _isChange = YES;
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
